#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
AI回复策略处理器
根据不同的任务类型调用不同的处理逻辑
"""

import json
import logging
import re
from typing import Dict, List, Optional, Tuple
from datetime import datetime

from config.prompts import TaskType, PromptConfig
from handlers.conversation_manager import ConversationManager
from services.llm import call_llm_gemini_image
from tasks import TaskManager

task_manager = TaskManager()

logger = logging.getLogger(__name__)

class AIResponseStrategy:
    """AI回复策略处理器"""
    
    def __init__(self, conversation_manager: ConversationManager):
        """
        初始化AI回复策略处理器
        
        Args:
            conversation_manager: 对话管理器
        """
        self.conversation_manager = conversation_manager
    
    def process_message(self, customer_id: str, message: str, response_data: Dict = None) -> Dict:
        """
        处理客户消息并生成AI回复
        
        Args:
            customer_id: 客户ID
            message: 客户消息
            response_data: AI解析后的回复数据（可选）
        Returns:
            Dict: 处理结果
        """
        logger.info(f"开始处理客户消息，客户ID: {customer_id}, 消息: {message}")
        
        # 检查会话状态，决定是否需要自动转回AI
        switched_back = self.conversation_manager.check_and_auto_switch(customer_id)
        if switched_back:
            logger.info(f"🔄 客户 {customer_id} 已自动转回AI服务")
        
        # 检查当前是否在人工服务状态
        is_human_service = self.conversation_manager.is_currently_human_service(customer_id)
        if is_human_service:
            # 检查是否是要求转回AI的消息
            switch_back_keywords = ['转回ai', '找ai', 'ai客服', '机器人', '智能客服', '转ai', '回到ai']
            message_lower = message.lower()
            
            if any(keyword in message_lower for keyword in switch_back_keywords):
                logger.info(f"🔄 客户 {customer_id} 要求转回AI服务")
                self.conversation_manager.switch_back_to_ai(customer_id)
                
                return {
                    "task_type": "查询商品信息",
                    "conversation_summary": [],
                    "customer_message": message,
                    "ai_response": "好的，已为您转回AI客服。我是AI助手，请问有什么可以帮助您的？",
                    "success": True,
                    "need_human": False
                }
            
            # 在人工服务状态下，更新沟通时间并直接返回人工服务提示
            self.conversation_manager.update_communication_time(customer_id)
            logger.info(f"👤 客户 {customer_id} 当前在人工服务状态，消息将转给人工处理")
            return {
                "task_type": "呼叫客服",
                "conversation_summary": [],
                "customer_message": message,
                "ai_response": "您当前正在与人工客服对话，请继续与人工客服沟通。",
                "success": True,
                "need_human": True
            }
        
        # 添加客户消息到对话历史
        session = self.conversation_manager.add_customer_message(customer_id, message)
        
        # 获取对话历史
        conversation_history = self.conversation_manager.get_relevant_history(customer_id)

        # 如果有AI解析结果，直接用它分支
        if response_data:
            ai_task_type = response_data.get("当前任务") or response_data.get("task_type")
            ai_response = response_data.get("AI客服回复", "")
            logger.info(f"AI解析出的当前任务: {ai_task_type}")
            logger.info(f"AI客服回复: {ai_response}")
            
            # 智能路由：只有在明确需要人工时才转人工
            if ai_task_type == "呼叫客服":
                # 检查是否刚刚从人工服务转回AI（避免立即又转人工）
                if session.human_service_start:
                    time_since_human_service = datetime.now() - session.human_service_start
                    if time_since_human_service.total_seconds() < 120:  # 2分钟内不重复转人工
                        logger.info(f"🔄 客户 {customer_id} 刚转回AI服务，暂时不转人工")
                        return {
                            "task_type": "查询商品信息",
                            "conversation_summary": [],
                            "customer_message": message,
                            "ai_response": "我是AI客服，请问有什么可以帮助您的？",
                            "success": True,
                            "need_human": False
                        }
                
                # 当AI识别出"呼叫客服"任务时，应该触发人工接管
                logger.info("🎯 检测到明确的人工客服请求，执行转接")
                task_map = {
                    "查询商品信息": "product_query",
                    "下单": "order_processing",
                    "呼叫客服": "customer_service"
                }
                selected_task = task_map.get(ai_task_type, "customer_service")
                logger.info(f"调用 task_manager._execute_task, 任务: {selected_task}")
                result = task_manager._execute_task(
                    selected_task,
                    message,
                    conversation_history,
                    customer_id
                )
                # 兼容AI回复结构
                result["task_type"] = ai_task_type
                return result
            else:
                # 下单、查询等任务，AI直接回复，不转人工
                logger.info(f"🎯 检测到{ai_task_type}任务，AI直接回复")
                
                # 添加AI回复到对话历史
                self.conversation_manager.add_ai_response(
                    customer_id, 
                    ai_response,
                    ai_task_type  # 直接传入字符串，不使用TaskType枚举
                )
                
                return {
                    "task_type": ai_task_type,
                    "conversation_summary": response_data.get("沟通摘要", []),
                    "customer_message": message,
                    "ai_response": ai_response,
                    "success": True,
                    "need_human": False  # 标记不需要人工
                }

        # 没有AI解析结果时，兼容老逻辑，自己调用AI
        # 统一生成 prompt，调用 AI 服务，获取 AI 回复
        prompt = PromptConfig.generate_prompt(
            current_message=message,
            conversation_history=conversation_history,
            task_type=None  # 这里不指定类型，让AI自己判断
        )
        try:
            logger.info("统一调用AI服务进行任务识别和回复...")
            ai_response = call_llm_gemini_image(prompt, {}, return_json=True)
            logger.info(f"AI服务返回: {ai_response}")
            response_data = self._parse_ai_response(ai_response)
            logger.info(f"解析后的回复数据: {response_data}")
            ai_task_type = response_data.get("当前任务") or response_data.get("task_type")
            ai_reply = response_data.get("AI客服回复", "")
            logger.info(f"AI解析出的当前任务: {ai_task_type}")
            logger.info(f"AI客服回复: {ai_reply}")
            
            # 智能路由：只有在明确需要人工时才转人工
            if ai_task_type == "呼叫客服":
                # 检查是否刚刚从人工服务转回AI（避免立即又转人工）
                if session.human_service_start:
                    time_since_human_service = datetime.now() - session.human_service_start
                    if time_since_human_service.total_seconds() < 120:  # 2分钟内不重复转人工
                        logger.info(f"🔄 客户 {customer_id} 刚转回AI服务，暂时不转人工")
                        return {
                            "task_type": "查询商品信息",
                            "conversation_summary": [],
                            "customer_message": message,
                            "ai_response": "我是AI客服，请问有什么可以帮助您的？",
                            "success": True,
                            "need_human": False
                        }
                
                # 当AI识别出"呼叫客服"任务时，应该触发人工接管
                logger.info("🎯 检测到明确的人工客服请求，执行转接")
                task_map = {
                    "查询商品信息": "product_query",
                    "下单": "order_processing",
                    "呼叫客服": "customer_service"
                }
                selected_task = task_map.get(ai_task_type, "customer_service")
                logger.info(f"调用 task_manager._execute_task, 任务: {selected_task}")
                result = task_manager._execute_task(
                    selected_task,
                    message,
                    conversation_history,
                    customer_id
                )
                # 兼容AI回复结构
                result["task_type"] = ai_task_type
                return result
            else:
                # 下单、查询等任务，AI直接回复，不转人工
                logger.info(f"🎯 检测到{ai_task_type}任务，AI直接回复")
                
                # 添加AI回复到对话历史
                self.conversation_manager.add_ai_response(
                    customer_id, 
                    ai_reply,
                    ai_task_type  # 直接传入字符串，不使用TaskType枚举
                )
                
                return {
                    "task_type": ai_task_type,
                    "conversation_summary": response_data.get("沟通摘要", []),
                    "customer_message": message,
                    "ai_response": ai_reply,
                    "success": True,
                    "need_human": False  # 标记不需要人工
                }
        except Exception as e:
            logger.error(f"AI处理失败: {str(e)}")
            return {
                "task_type": "呼叫客服",
                "conversation_summary": [],
                "customer_message": message,
                "ai_response": "请稍等，正在呼叫人工客服。",
                "success": False,
                "error": str(e),
                "need_human": True  # 出错时转人工
            }
    
    def _handle_product_query(self, customer_id: str, message: str, response_data: Dict = None) -> Dict:
        """
        处理商品查询请求
        
        Args:
            customer_id: 客户ID
            message: 客户消息
            response_data: AI解析后的回复数据（可选）
            
        Returns:
            Dict: 处理结果
        """
        logger.info(f"开始处理商品查询，客户ID: {customer_id}")
        
        # 只处理AI解析数据
        if response_data:
            ai_reply = response_data.get("AI客服回复", "")
            conversation_summary = response_data.get("沟通摘要", [])
            
            # 添加AI回复到对话历史
            self.conversation_manager.add_ai_response(
                customer_id, 
                ai_reply,
                TaskType.QUERY_PRODUCT
            )
            
            return {
                "task_type": TaskType.QUERY_PRODUCT.value,
                "conversation_summary": conversation_summary,
                "customer_message": message,
                "ai_response": ai_reply,
                "success": True
            }
        
        # 没有AI解析数据时，返回错误
        logger.error("_handle_product_query 必须提供 response_data")
        return {
            "task_type": TaskType.QUERY_PRODUCT.value,
            "conversation_summary": [],
            "customer_message": message,
            "ai_response": "抱歉，处理您的查询时出现了问题，请稍后再试。",
            "success": False,
            "error": "未提供AI解析数据"
        }

    def _handle_order_request(self, customer_id: str, message: str, response_data: Dict = None) -> Dict:
        """
        处理下单请求
        
        Args:
            customer_id: 客户ID
            message: 客户消息
            response_data: AI解析后的回复数据（可选）
            
        Returns:
            Dict: 处理结果
        """
        current_order_info = self.conversation_manager.get_order_info(customer_id) or {}
        order_info = self._extract_order_info(message, current_order_info)
        self.conversation_manager.update_order_info(customer_id, order_info)
        
        if response_data:
            ai_reply = response_data.get("AI客服回复", "")
            conversation_summary = response_data.get("沟通摘要", [])
            self.conversation_manager.add_ai_response(
                customer_id, 
                ai_reply,
                TaskType.PLACE_ORDER
            )
            return {
                "task_type": TaskType.PLACE_ORDER.value,
                "conversation_summary": conversation_summary,
                "customer_message": message,
                "ai_response": ai_reply,
                "order_info": order_info,
                "success": True
            }
        logger.error("_handle_order_request 必须提供 response_data")
        return {
            "task_type": TaskType.PLACE_ORDER.value,
            "conversation_summary": [],
            "customer_message": message,
            "ai_response": "抱歉，处理您的下单请求时出现了问题，请稍后再试。",
            "order_info": order_info,
            "success": False,
            "error": "未提供AI解析数据"
        }

    def _handle_human_service_request(self, customer_id: str, message: str, response_data: Dict = None) -> Dict:
        """
        处理人工客服请求
        
        Args:
            customer_id: 客户ID
            message: 客户消息
            response_data: AI解析后的回复数据（可选）
            
        Returns:
            Dict: 处理结果
        """
        if response_data:
            ai_reply = response_data.get("AI客服回复", "")
            conversation_summary = response_data.get("沟通摘要", [])
            self.conversation_manager.add_ai_response(
                customer_id, 
                ai_reply,
                TaskType.CALL_HUMAN
            )
            return {
                "task_type": TaskType.CALL_HUMAN.value,
                "conversation_summary": conversation_summary,
                "customer_message": message,
                "ai_response": ai_reply,
                "success": True
            }
        logger.error("_handle_human_service_request 必须提供 response_data")
        return {
            "task_type": TaskType.CALL_HUMAN.value,
            "conversation_summary": [],
            "customer_message": message,
            "ai_response": "请稍等，正在呼叫人工客服。",
            "success": False,
            "error": "未提供AI解析数据"
        }
    
    def _parse_ai_response(self, ai_response: str) -> Dict:
        """
        解析AI回复
        
        Args:
            ai_response: AI回复内容
            
        Returns:
            Dict: 解析后的数据
        """
        try:
            # 尝试解析JSON
            if isinstance(ai_response, str):
                # 清理可能的Markdown代码块标记
                clean_response = re.sub(r'^```(json)?\s*\n', '', ai_response)
                clean_response = re.sub(r'\n```\s*$', '', clean_response)
                response_data = json.loads(clean_response)
            else:
                response_data = ai_response
            
            return response_data
            
        except json.JSONDecodeError as e:
            logger.error(f"解析AI回复失败: {str(e)}")
            return {
                "当前任务": "呼叫客服",
                "沟通摘要": [],
                "客户最后一条消息": "",
                "AI客服回复": "请稍等，正在呼叫人工客服。"
            }
    
    def _extract_order_info(self, message: str, current_order_info: Dict) -> Dict:
        """
        从消息中提取订单信息
        
        Args:
            message: 客户消息
            current_order_info: 当前订单信息
            
        Returns:
            Dict: 更新后的订单信息
        """
        order_info = current_order_info.copy()
        
        # 提取数量信息
        quantity_pattern = r'(\d+)\s*(件|个|套|箱|包|盒)'
        quantities = re.findall(quantity_pattern, message)
        if quantities:
            order_info["quantities"] = quantities
        
        # 提取颜色信息
        color_pattern = r'(红色|蓝色|绿色|黄色|黑色|白色|紫色|粉色|橙色|灰色)'
        colors = re.findall(color_pattern, message)
        if colors:
            order_info["colors"] = colors
        
        # 提取收货信息
        if "收货人" in message or "姓名" in message:
            # 这里可以添加更复杂的收货信息提取逻辑
            pass
        
        return order_info
    
    def get_conversation_summary(self, customer_id: str) -> List[str]:
        """
        获取对话摘要
        
        Args:
            customer_id: 客户ID
            
        Returns:
            List[str]: 对话摘要
        """
        return self.conversation_manager.generate_conversation_summary(customer_id)
    
    def get_session_stats(self) -> Dict:
        """
        获取会话统计信息
        
        Returns:
            Dict: 统计信息
        """
        return self.conversation_manager.get_session_stats() 